package games.gong.durid.service.impl;

import games.gong.durid.entity.Permission;
import games.gong.durid.entity.Role;
import games.gong.durid.entity.User;
import games.gong.durid.mapper.UserMapper;
import games.gong.durid.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @PackageName games.gong.durid.service
 * @projectName springboot
 * @Description 用户服务实现类
 * @Author games
 * @Date 2025/8/10 上午10:23
 * @Version 1.0
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public int addUser(User user) {
        // 忽略客户端传递的时间字段，由服务端生成
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 密码加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        int result = userMapper.insert(user);
        return result;
    }

    @Override
    public int deleteUser(Long id) {
        int result = userMapper.deleteById(id);
        return result;
    }

    @Override
    public int updateUser(User user) {
        // 忽略客户端传递的时间字段，由服务端生成
        user.setUpdateTime(LocalDateTime.now());
        // 密码加密
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        int result = userMapper.update(user);
        return result;
    }

    @Override
    public User getUserById(Long id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = userMapper.selectAll();
        return users;
    }

    @Override
    public User getUserByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        return user;
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        return userMapper.selectRolesByUserId(userId);
    }

    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return userMapper.selectPermissionsByRoleId(roleId);
    }
}